Warm-up problem
Install the package beepr and run the command beepr::beep(). beepr::beep(k) can play k=1-11 sounds. (See ?beep for a list of sounds).
A. Write loops and functions.
Write a loop to listen to each sound. Use Sys.sleep() to pause 2 seconds between each call to beep.
Modify the loop to pause a random duration of time. You can set your own parameters for ‘what a random duration of time’ means.
B. How can the beepr::beep() function be helpful? What does this say about R being a scripting language?
C. After calling library(beepr), the beep function can be directly called as beep(). Why can it be helpful to call beepr::beep()?
D. (If time allows) Create a function that takes two inputs: a numeric vector and sound. Write a loop that one-at-a-time calculates the cumulative sum each element of the vector (don’t use the cumsum function). Play a beep at the end of calculation using the sound input. The output should be a two-column matrix with the original vector (column 1) and the cumsum (column 2). Check you answer using the cumsum function.
Note: Question D is designed to practice working with loops and building up the output result. One-at-a-time calculations discouraged whenever avoidable. In practice, it would be better to use the cumsum function.
This week’s lesson
Focus on foundations
Many of the this week’s topics will be familiar, and it may be tempting to gloss over. However, there are important foundational concepts which can strengthen understanding and efficient coding.
Key concepts
In addition to general concepts, the below strategies improve efficient, reproducible code:
- Use matrices rather than data.frames whenever possible; they use less memory
- Use names for indexing and filtering; it is transparent and less error-prone
- Pre-initialize data-structures to be filled rather than saving over existing objects
- Consider if there are ways to reduce unnecesary calculations